// part1:C13:ex13.30.cpp
// class HasPtr.
// swap function.
#include <iostream>
#include <string>
using namespace std;
class HasPtr
{
public:
  // constructor allocate new string and new count,
  // set count = 1.
  HasPtr(const string &s = string()):
    ps(new string(s)), i(0), use(new size_t(1)){}
  // copy constructor has three data members,
  // increment count.
  HasPtr(const HasPtr &p):
    ps(p.ps), i(p.i), use(p.use) { ++*use; }
  HasPtr& operator=(const HasPtr&);
  HasPtr& operator=(const string&);
  string& operator*();
  ~HasPtr();
  swap(HasPtr &lhs, HasPtr &rhs);
  private:
    string *ps;
    int i;
    size_t *use;
  };

HasPtr::~HasPtr()
{
  if (--*use == 0)
  {
    delete ps;
    delete use;
  }
}


HasPtr& HasPtr::operator=(const HasPtr& &rhs)
{
  ++*rhs.use;  
  if (--*use == 0)
  {
    delete ps;
    delete use;
  }

  ps = rhs.ps;
  i = rhs.i;
  use = rhs.use;

  return *this;
}
HasPtr& HasPtr::operator=(const string& &rhs)
{
  *ps = rhs;
  return *this;
}
string& HasPtr::operator*()
{
  return *ps;
}

inline HasPtr::swap(HasPtr &lhs, HasPtr &rhs) {
  cout << "swap " << *lhs.ps << " and " << *rhs.ps << endl;
  // swap pointer, not string data
  swap(lhs.ps, rhs.ps);
  // swap int member
  swap(lhs.i,rhs.i);
}
int main(int argc, char *argv[])
{
  HasPtr h("hi mom!");
  // h2, h3 point to different string
  HasPtr h2(h);
  HasPtr h3 = h;

  h2 = "hi dad!";
  h3 = "hi son!";
  swap(h2, h3);
  cout << "h: " << *h << endl;
  cout << "h2: " << *h2 << endl;
  cout << "h3: " << *h3 << endl;

  return 0;
}
